<?php
class MsgStack implements IteratorAggregate {
  
  protected $messages;
  
  public static function getInstance() {
    $stack = unserialize($_SESSION['msg_stack']);
    if ($stack instanceof MsgStack) return $stack;
    $stack = new MsgStack();
    $_SESSION['msg_stack'] = $stack;
    return $stack;
  }
  
  public function __construct() {
    $this->messages = array();
  }
  
  public function getIterator() {
    return new ArrayIterator( $this->messages );
  } 
  
  public function __get($pMsgKey) {
    if (array_key_exists($pMsgKey, $this->messages)) return $this->messages[$pMsgKey];
    return null;
  }
  
  public function __set($pMsgKey, $pVal) {
    $this->messages[$pMsgKey] = $pVal;
    $_SESSION['msg_stack'] = serialize($this);
  }  
}
